<template>
    <!-- Main content -->
    <div>
        <div class="row">
            <div class="col-xs-12">
                <theme-box title="商品字典列表">
                    <form class="form-inline" @submit.prevent v-el:form>
                        <form-input title="字典内容" :up-table="true" name="dictValue"></form-input>
                        <form-select title="分类类型" :sreach="true" :up-table="true" :options="typeOptions"
                                     name="dictType"></form-select>
                        <span class="pull-right">
                            <button type="reset" @click="reset" class="btn btn-warning pull-right">重置</button>
                        <v-button theme="primary" @click="search" class="pull-right">查询</v-button>
                        </span>
                    </form>
                    <table class="table table-bordered table-striped" style="width:100%" v-el:table>
                    </table>
                </theme-box>
            </div>
            <!-- /.col -->
        </div>
        <modal-container title="编辑" v-el:modal v-ref:modal class="edit-modal" theme="big">
            <form @submit.prevent @reset.prevent v-el:mform>
                <div class="modal-body">
                    <table-modal :item="item" :columns-set="columnsSet" v-ref:item></table-modal>
                </div>

                <div class="modal-footer">
                    <v-button class="pull--left" data-dismiss="modal" @click="resetBindDrag">关闭</v-button>
                    <v-button theme="primary" type="submit">保存</v-button>
                </div>
            </form>

        </modal-container>
        <!-- /.row -->
    </div>
    <!-- /.content -->
</template>

<style lang="less" scoped>
    .form-inline .btn + .btn {
        margin-right: 10px;
    }

</style>
<script>
    //解决datatables弹窗警告
    $.fn.dataTable.ext.errMode = 'none';
    import {
        dateTime,
        createDataTable
    } from 'ui/collections/general.js'
    var serialize = require('form-serialize');

    var dataTable;
    var columnsSet;
    export default {
        data: () => ({
            item: {},
            columnsSet: [],
            typeOptions: [{
                key: "全选",
                value: ""
            }, {
                key: "主分类",
                value: "0"
            }, {
                key: "次分类",
                value: "1"
            }]
        }),

        methods: {
            //还原弹出框位置
            resetBindDrag() {
                this.$refs.modal._resetBindDrag();
            },
            //查询按钮
            search: function () {
                dataTable.ajax.reload();
            },
            //重置按钮
            reset: function () {
                $(".form-inline")[0].reset();
                dataTable.ajax.reload();
            }
        },
        created() {
            //datatable所用数组
            columnsSet = [{
                title: "编号",
                data: "dictId",
                edit: true,
                readonly: true,
                className: "operate"
            }, {
                title: "字典类型",
                data: "dictType",
                options: [{key: "主分类", value: "0"}, {key: "次分类", value: "1"}],
                className: "operate",
                render: function (data) {
                    return (data == 0) ? "主分类" : "次分类"
                }
            }, {
                title: "上级分类类型",
                data: "upperDictId",
                visible:false,
                className: "operate"
            },{
                title: "上级分类类型",
                data: "upperDictValue",
                className: "operate"
            }, {
                title: "字典内容",
                data: "dictValue",
                edit: true,
                className: "operate"
            }, {
                title: "分类描述",
                data: "dictDsc",
                edit: true,
                className: "operate",
                className: "wrap"
            }, {
                title: "分类顺序",
                data: "typeOrder",
                edit: true,
                readonly: false,
                className: "operate",
                render(data, type, row){
                    if (row.dictType == "1") {
                        return ""
                    } else {
                        return data
                    }
                }
            }, {
                title: "分类ICO名",
                data: "icoName",
                edit: true,
                className: "operate",
                className: "wrap"
            }, {
                title: "相关操作",
                className: "operate",
                width: "160px",
                render: function (value, type, row) {
                    return `
                            <button type="button" class="btn btn-primary btn-sm edit">编辑</button>
                            <button type="button" class="btn btn-danger btn-sm delete">删除</button>
                        `
                }
            }]
        },
        ready: async function () {
            var typeWatch = function () {
            };
            dateTime({
                format: "yyyy-mm-dd",
                minView: "2"
            })
            this.$set("columnsSet", columnsSet)
            var self = this;
            //创建dataTable
            dataTable = $(this.$els.table).DataTable({
                "columns": this.columnsSet, //定义列
                "ajax": async function (data, callback, settings) {
                    var page = [{
                        "name": "iDisplayStart",
                        "value": 1 + data.start / data.length
                    }, {
                        "name": "iDisplayLength",
                        "value": data.length
                    }];
                    //表单序列化数据
                    var _data = serialize(self.$els.form, {
                        hash: true,
                        disabled: true,
                        empty: true
                    });
                    _data.aoData = JSON.stringify(page);
                    //发送请求
                    var result = await self.$post({
                        url: "/api/v1" + projectName_Url + "/plat/dict/query",
                        data: _data,
                        method: "POST"
                    })
                    if (result.respCode != "00") {
                        Midway.alert({
                            title: "操作失败",
                            content: result.content
                        })
                    }
                    callback({
                        recordsTotal: result.content.total,
                        recordsFiltered: result.content.total,
                        data: result.content.result || []
                    })
                }
            });


            $(self.$el).on("click", ".edit", function () {
                var Row = $(this).closest('tr').get(0);
                const dataArray = JSON.parse(JSON.stringify(dataTable.row(Row).data()));
                self.item = dataArray;
                dateTime()

                //监听分类类型的值
                typeWatch()
                typeWatch = self.$refs.item.$watch("item.dictType", function (v) {
                    if (v == '0') {
                        self.columnsSet.find(data => data.data == "typeOrder").edit = true;
                        self.columnsSet.find(data => data.data == "icoName").edit = true;
                    } else {
                        self.columnsSet.find(data => data.data == "typeOrder").edit = false;
                        self.columnsSet.find(data => data.data == "icoName").edit = false;

                    }
                });
                //修改弹框里的分类类型
                self.$post({
                    url: "/api/v1" + projectName_Url + "/list/caterdict/back_type/0",
                    method: "GET"
                }).then(response => {
                    let _array = [];
                    if(response.content.info != null){
                        for(let i=0;i<response.content.info.length;i++){
                            _array.push({value:response.content.info[i].value,key:response.content.info[i].key});
                        }
                    }
                    self.$set("columnsSet[2].options",_array)
                }, response => {
                });

                //编辑框验证、保存、提交
                $(self.$els.mform).validate(self.item.valdate = {
                    async submitHandler() {
                        var form = self.$els.mform;
                        var _data = serialize(form, {hash: true, disabled: true, empty: true});

                        var result = await self.$post({
                            url: "/api/v1" + projectName_Url + "/plat/dict/" + _data.dictId,
                            data: _data,
                            method: "PUT"
                        });
                        Midway.alert({title: "操作提示", content: result.errorInfo})
                        dataTable.ajax.reload(null, false);
                        $(self.$els.modal).modal('hide');
                        self.resetBindDrag()
                    },
                    rules: {
                        dictId: {
                            required: true
                        }, dictValue: {
                            required: true,
                            stringMaxLength: 20
                        }, dictDsc: {
                            stringMaxLength: 16
                        }, dictType: {
                            required: true
                        }, typeOrder: {
                            int: true,
                            min: 1,
                            maxlength: 2,
                            required: true
                        }, icoName: {
                            required: true,
                            stringMaxLength: 8
                        }
                    }
                });

                //如果是次分类 内容最多输入5个字
                $(self.$els.mform.dictValue).rules("remove", "maxlength");
                if (dataArray.dictType == "1") {
                    $(self.$els.mform.dictValue).rules("add", {
                        maxlength: 5
                    });
                } else {
                    $(self.$els.mform.dictValue).rules("add", {
                        maxlength: 20
                    });
                };
                $('select[name="dictType"]').change(function () {
                    $(self.$els.mform.dictValue).rules("remove", "maxlength");
                    if (dataArray.dictType == "1") {
                        $(self.$els.mform.dictValue).rules("add", {
                            maxlength: 5
                        });
                    } else {
                        $(self.$els.mform.dictValue).rules("add", {
                            maxlength: 20
                        });
                    };
                    $(self.$els.mform).valid();
                });

                //检查是否验证通过
                $(self.$els.mform).valid();

                $(self.$els.modal).modal('show');
            });

            $(self.$el).on("click", ".delete", async function () {
                var Row = $(this).closest('tr').get(0);
                var value = dataTable.row(Row).data().dictValue;
                var id = dataTable.row(Row).data().dictId;

                await Midway.confirm({
                    title: "删除商品字典",
                    content: "是否要删除商品字典:" + value + "?"
                })
                var result = await self.$post({
                    url: "/api/v1" + projectName_Url + "/plat/dict/" + id,
                    method: "DELETE"
                });
                Midway.alert({title: "操作提示", content: result.errorInfo})
                dataTable.ajax.reload();
            })
        },
        beforeDestroy() {
            $(this.$el).off("click")
        }
    }
</script>
